<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\AuthDepartment;
use app\admin\model\finance\extract\Season;
use app\admin\model\finance\extract\Week;
use app\common\controller\Yangliu;
use app\admin\model\School;
use app\common\model\Flow;
use app\common\model\task\Detail;
use app\common\model\task\Gift;
use app\common\model\task\Outer as TaskOuter;
use app\common\model\task\See;
use app\common\model\task\Sign;
use EasyWeChat\Factory;
use think\Db;
use think\Env;
use workflow\workflow;


/**
 * 外联任务单
 */
class Outer extends Yangliu
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $model;
    protected $school;
    protected $jurisdiction;
    protected $week;
    protected $app;
    protected $token;
    protected $sign;
    protected $gift;
    protected $detail;
    protected $see;
    protected $flow;
    protected $tableName;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new TaskOuter();
        $this->sign = new Sign();
        $this->gift = new Gift();
        $this->detail = new Detail();
        $this->see = new See();
        $this->flow = new Flow();
        $this->school = new School();
        $this->jurisdiction = $this->auth->Auth();
        //获取表名
        $this->tableName = str_replace('hdyj_','',$this->model->getQuery()->getTable());
        //实例化企业微信
        $this->app = Factory::work([
            'agent_id' => Env::get('outer.agent_id'),
            'corp_id' => Env::get('outer.corp_id'),
            'secret'   => Env::get('outer.secret'),
            'response_type' => Env::get('outer.response_type'),
            'log' => [
                'level' => Env::get('outer.level'),
                'file' => __DIR__.Env::get('outer.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('outer.scopes'),
                'callback' => Env::get('outer.callback')
            ]
        ]);
        $this->token = $this->app->access_token->getToken();
    }

    /**
     * @ApiTitle    (外联任务单列表)
     * @ApiSummary  (外联任务单分页)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/index)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="page", type="integer", required=false, description="第几页,默认第一页")
     * @ApiParams   (name="limit", type="string", required=false, description="每页条数,默认10条")
     * @ApiParams   (name="where[filiale]", type="array", required=false, description="查询条件,分公司ID")
     * @ApiParams   (name="where[week_id]", type="array", required=false, description="查询条件,周次ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="total", type="integer", required=true, description="总条数")
     * @ApiReturnParams   (name="per_page", type="integer", required=true, description="每页数")
     * @ApiReturnParams   (name="current_page", type="integer", required=true, description="当前页")
     * @ApiReturnParams   (name="last_page", type="integer", required=true, description="最后一页")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="主键ID")
     * @ApiReturnParams   (name="userid", type="string", required=true, description="添加人ID hdyj_admin")
     * @ApiReturnParams   (name="week_id", type="integer", required=true, description="周ID hdyj_finance_extract_week")
     * @ApiReturnParams   (name="school_id", type="integer", required=true, description="学校ID hdyj_school")
     * @ApiReturnParams   (name="external", type="string", required=true, description="外联")
     * @ApiReturnParams   (name="status", type="integer", required=true, description="状态")
     * @ApiReturnParams   (name="createtime", type="integer", required=true, description="创建时间")
     * @ApiReturnParams   (name="updatetime", type="integer", required=true, description="更新时间")
     * @ApiReturnParams   (name="filiale", type="integer", required=true, description="分公司ID")
     * @ApiReturnParams   (name="filiale_name", type="string", required=true, description="分公司名称")
     * @ApiReturnParams   (name="runner", type="string", required=true, description="合跑外联")
     * @ApiReturnParams   (name="userid_text", type="string", required=true, description="添加人名称")
     * @ApiReturnParams   (name="week_id_text", type="string", required=true, description="周数据名称")
     * @ApiReturnParams   (name="school_id_text", type="string", required=true, description="学校名称")
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1574932827",
    "data": {
    "total": 57,
    "per_page": "1",
    "current_page": 1,
    "last_page": 57,
    "data": [
    {
    "id": 1,
    "userid": "yangliu",
    "week_id": 2,
    "external": "yangliu",
    "status": 1,
    "createtime": 1574908660,
    "filiale": 1,
    "filiale_name": "北京分公司",
    "runner": null,
    "school_id": 1,
    "userid_text": "杨柳",
    "week_id_text": "08.20-08.26周数据",
    "school_id_text": "北京市第四中学"
    }
    ]
    }
    })
     */
    public function index()
    {
        list($where, $order, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->field('id,userid,week_id,external,status,createtime,filiale,filiale_name,runner,school_id')
            ->order($order)
            ->paginate($this->request->request('Pagesize',$limit),false);
        $this->success('',$list);
    }

    /**
     * @ApiTitle    (新增外联任务)
     * @ApiSummary  (领导新增外联任务)
     * @ApiMethod   (POSt)
     * @ApiRoute    (/api/outer/add)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="row[week_id]", type="array", required=true, description="周计划ID")
     * @ApiParams   (name="row[school_id]", type="array", required=true, description="学校ID")
     * @ApiParams   (name="row[external]", type="array", required=true, description="外联")
     * @ApiParams   (name="row[runner]", type="array", required=false, description="合跑外联 例如:1,2,3")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     *  * @ApiReturn   ({
    "code": 1,
    "msg": "新增成功！",
    "time": "1574934820",
    "data": {
    "week_id": "1",
    "school_id": "2",
    "external": "yangliu",
    "runner": "yangliu,SunDan",
    "filiale": "1",
    "filiale_name": "北京分公司",
    "userid": "SunDan",
    "createtime": 1574934820,
    "updatetime": 1574934820,
    "id": "60",
    "userid_text": "孙丹",
    "week_id_text": null,
    "school_id_text": "测试学校"
    }
    })
     */
    public function add()
    {
        $row = $this->request->request('row/a');
        $row['userid'] = $this->auth->userid;
        $week = Week::get($row['week_id']);
        $DepartmentName = AuthDepartment::getName($week['department']);
        $row['filiale'] = $week['department'];
        $row['filiale_name'] = $DepartmentName;
        $row['status'] = 0;
        if($res = $this->model->create($row))
        {
            //通知外联  抄送合跑人
            // userid  url  text
            $title = '有新的任务';
            $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div><div class=\"normal\">".$this->auth->username."发布了新的任务单</div><div class=\"highlight\">请您在本周内完成任务</div>";
            $this->ExternalMsg($row['external']."|".$row['runner'],'http://oa.fc62.com/outer/#/Taskinfo?id='.$res['id'],$title,$text);
            $this->success('新增完成！',$res);
        }
        $this->error('新增失败！');
    }

    /**
     * @ApiTitle    (任务单作废)
     * @ApiSummary  (没有签到记录，没有拜访记录。才可以作废)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/outerCancel/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="array", required=true, description="任务单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     *  * @ApiReturn   ({
    "code": 1,
    "msg": "操作成功！",
    "time": "1574934820",
    "data": null
    })
     */
    public function outerCancel($outerid = null)
    {
        $row = $this->model->get($outerid);
        $row->status = 4;
        $row->save();
        $this->success('操作成功！');
    }


    /**
     * @ApiTitle    (查看外联任务单)
     * @ApiSummary  (查看外联任务单)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/outer/ids/{ids})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="ids", type="integer", required=true, description="外联任务单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="class", type="integer", required=false, description="总班级数量")
     * @ApiReturnParams   (name="total_number", type="integer", required=false, description="总人数")
     * @ApiReturnParams   (name="science_num", type="integer", required=false, description="文科班数量")
     * @ApiReturnParams   (name="arts_num", type="integer", required=false, description="理科班数量")
     * @ApiReturnParams   (name="science_class", type="integer", required=false, description="文科生数量")
     * @ApiReturnParams   (name="arts_class", type="integer", required=false, description="理科生数量")
     * @ApiReturnParams   (name="up_year", type="integer", required=false, description="上学年本校是否 1 是 2否")
     * @ApiReturnParams   (name="sales_volume", type="integer", required=false, description="上学年销量")
     * @ApiReturnParams   (name="category", type="integer", required=false, description="学校分类")
     * @ApiReturnParams   (name="external", type="integer", required=false, description="外联ID")
     * @ApiReturnParams   (name="external_text", type="integer", required=false, description="外联名称")
     * @ApiReturnParams   (name="filiale", type="integer", required=false, description="分公司ID")
     * @ApiReturnParams   (name="filiale_name", type="integer", required=false, description="分公司名称")
     * @ApiReturnParams   (name="runner", type="integer", required=false, description="合跑外联ID")
     * @ApiReturnParams   (name="cancel", type="Boole", required=true, description="true 可作废 false 不可作废")
     * @ApiReturnParams   (name="status", type="integer", required=false, description="状态：0=新发布 1=流程中 2=审核通过 -1=已驳回 3=已接收 ")
     *  * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1575622776",
    "data": {
    "outer": {
    "id": 1,
    "userid": "yangliu",
    "week_id": 2,
    "school_id": 1,
    "external": "yangliu",
    "status": 1,
    "createtime": 1574908660,
    "updatetime": 1574908660,
    "filiale": 33,
    "filiale_name": "北京分公司",
    "runner": null,
    "userid_text": "杨柳",
    "week_id_text": "08.20-08.26周数据",
    "school_id_text": "北京市第四中学",
    "status_text": "新发布",
    "stateclass": "fabu",
    "external_text": "杨柳",
    "createtime_text": "2019-11-28 10:37:40"
    },
    "school": {
    "id": 1,
    "name": "北京市第四中学",
    "province": 1,
    "city": 2,
    "area": 4,
    "address": "西黄城根北街甲2号",
    "category": "A",
    "type": "3",
    "class": 0,
    "total_number": 0,
    "textbook_edition": "",
    "policylist": null,
    "is_schoolsdata": "1",
    "total_score": "",
    "volume": null,
    "teaching_order": null,
    "bookstore": "",
    "createtime": 1542265427,
    "updatetime": 1575599770,
    "science_num": 111,
    "arts_num": 111,
    "science_class": 111,
    "arts_class": 111,
    "up_year": 1,
    "sales_volume": 111,
    "category_text": "A",
    "type_text": "高中",
    "policylist_text": "",
    "is_schoolsdata_text": "Is_schoolsdata 1",
    "volume_text": "",
    "teaching_order_text": "",
    "province_text": "北京",
    "city_text": "北京市",
    "area_text": "西城区"
    },
    "blad": [
    {
    "id": 3,
    "sign_id": 1,
    "pro_id": 1,
    "type": 1,
    "num": "12",
    "createtime": 1575452219,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "样书"
    },
    {
    "id": 1,
    "sign_id": 1,
    "pro_id": 2,
    "type": 1,
    "num": "8",
    "createtime": 1575452110,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J2",
    "pro_img": "",
    "type_text": "样书"
    }
    ],
    "donat": [
    {
    "id": 4,
    "sign_id": 1,
    "pro_id": 1,
    "type": 2,
    "num": "12",
    "createtime": 1575452231,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "赠书"
    }
    ],
    "gift": [
    {
    "id": 1,
    "sign_id": 1,
    "rule": "50面值",
    "type": "充值卡",
    "num": "200",
    "createtime": 1575449557
    }
    ]
    }
    })
     */
    public function outer($ids = null)
    {
        $row['outer'] = $this->model->get($ids);
        if($row['outer']['external'] == $this->auth->userid && $row['outer']->status == 0)
        {
            $row['outer']->status = 3;//已经接收
            $row['outer']->save();
        }
        //查询学校的基本情况
        $row['school'] =  School::get($row['outer']['school_id']);
        $row['outer']['cancel'] = false;
        //获取此任务单的所有签到表id
        $inIds = $this->sign->where('outer_id',$row['outer']['id'])->column('id');
        $seeRow  = $this->see->get(['outer_id'=>$ids]);
        if(empty($inIds) && !$seeRow)
        {
            $row['outer']['cancel'] = true;
        }
        //样书赠书明细
        $row['blad'] = $this->detail->field('id,sign_id,pro_id,type,sum(num) as num,createtime')
            ->where(['sign_id'=>['in',$inIds],'type'=>1])
            ->group('pro_id')
            ->select();
        $row['donat'] = $this->detail->field('id,sign_id,pro_id,type,sum(num) as num,createtime')
            ->where(['sign_id'=>['in',$inIds],'type'=>2])
            ->group('pro_id')
            ->select();
        //礼品明细
        $row['gift'] = $this->gift->field('id,sign_id,rule,type,sum(num) as num,createtime')
            ->where(['sign_id'=>['in',$inIds]])
            ->group('type')
            ->select();
        $this->success('',$row);
    }

    /**
     * @ApiTitle    ( 外联任务单更新数据 )
     * @ApiSummary  ( 外联任务单更新数据 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/outerEdit/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="string", required=true, description="id")
     * @ApiParams   (name="update[schoolIs]", type="string", required=false, description="学校情况汇总")
     * @ApiParams   (name="update[receipttime]", type="string", required=false, description="回执时间")
     * @ApiParams   (name="update[receiptnum]", type="string", required=false, description="回执数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    code: 0,
    msg: "没有要更新的数据",
    time: "1575615020",
    data: null
    })
     */
    public function outerEdit($id=null)
    {
        if(!$row = $this->model->get($id))
        {
            $this->error('请求参数ids未获取到');
        }
        if(!$data = $this->request->request('update/a')){
            $this->error('没有要更新的数据');
        }
        $this->model->where('id',$id)->update($data);
        $this->success('修改成功');
    }

    /**
     * @ApiTitle    (签到详情)
     * @ApiSummary  ( 签到详情)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/sign/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="integer", required=true, description="签到id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="latitude", type="string", required=false, description="纬度")
     * @ApiReturnParams   (name="longitude", type="string", required=false, description="经度")
     * @ApiReturnParams   (name="address", type="string", required=false, description="详细地址")
     * @ApiReturnParams   (name="images", type="array", required=false, description="图片")
     * @ApiReturnParams   (name="createtime", type="integer", required=false, description="创建时间")
     * @ApiReturnParams   (name="userid_text", type="integer", required=false, description="用户名称")
     * @ApiReturn   ({
    "code": 1,
    "msg": "查看记录",
    "time": "1575619313",
    "data": {
    "sign": {
    "id": 1,
    "outer_id": 1,
    "latitude": "1",
    "longitude": "2",
    "address": "",
    "images": "http://oaimg.fc62.com/uploads/20191206/89d15aaf090bcdb5c6e41795a04159bc.png,http://oaimg.fc62.com/uploads/20191206/6f59204606dbb57fd7c851aef338fad1.jpeg",
    "createtime": 1575488800,
    "updatetime": null,
    "userid": "yangliu",
    "schoolIs": null,
    "receipttime": null,
    "receiptnum": null,
    "power": true,
    "userid_text": "杨柳",
    "createtime_text": "2019-12-05 03:46:40"
    },
    "school": {
    "id": 1,
    "name": "北京市第四中学",
    "province": 1,
    "city": 2,
    "area": 4,
    "address": "西黄城根北街甲2号",
    "category": "A",
    "type": "3",
    "class": 0,
    "total_number": 0,
    "textbook_edition": "",
    "policylist": null,
    "is_schoolsdata": "1",
    "total_score": "",
    "volume": null,
    "teaching_order": null,
    "bookstore": "",
    "createtime": 1542265427,
    "updatetime": 1575599770,
    "science_num": 111,
    "arts_num": 111,
    "science_class": 111,
    "arts_class": 111,
    "up_year": 1,
    "sales_volume": 111,
    "category_text": "A",
    "type_text": "高中",
    "policylist_text": "",
    "is_schoolsdata_text": "Is_schoolsdata 1",
    "volume_text": "",
    "teaching_order_text": "",
    "province_text": "北京",
    "city_text": "北京市",
    "area_text": "西城区"
    },
    "blad": [
    {
    "id": 3,
    "sign_id": 1,
    "pro_id": 1,
    "type": 1,
    "num": "24",
    "createtime": 1575452219,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "样书"
    },
    {
    "id": 1,
    "sign_id": 1,
    "pro_id": 2,
    "type": 1,
    "num": "8",
    "createtime": 1575452110,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J2",
    "pro_img": "",
    "type_text": "样书"
    }
    ],
    "donat": [],
    "gift": [
    {
    "id": 1,
    "sign_id": 1,
    "rule": "50面值",
    "type": "充值卡",
    "num": "200",
    "createtime": 1575449557
    }
    ]
    }
    })
     */
    public function sign($id = null)
    {
        $list['sign'] = $this->sign->get($id);
        $list['sign']['power']  = true;
        $list['sign']['images']  = json_decode($list['sign']['images'],true);

        //学校的数据
        $list['outer'] = $this->model->get($list['sign']['outer_id']);
        $list['school'] = School::get($list['outer']->school_id);
        //样书赠书明细
        $list['blad'] = $this->detail
            ->where(['sign_id'=>$list['sign']['id'],'type'=>1])
            ->select();
        $list['donat'] = $this->detail
            ->where(['sign_id'=>$list['sign']['id'],'type'=>2])
            ->select();
        //礼品明细
        $list['gift'] = $this->gift
            ->where('sign_id',$list['sign']['id'])
            ->select();
        //判断是否当天数据 当天可修改 否则只能查看
        $list['sign']['power'] = date('d',$list['sign']['createtime']) == date('d',time()) ? false : true;
        $this->success('查看记录',$list);
    }

    /**
     * @ApiTitle    (更新签到)
     * @ApiSummary  ( 更新签到 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/signEdit/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="string", required=true, description="id")
     * @ApiParams   (name="update[images]", type="string", required=false, description="签到图片")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    code: 0,
    msg: "没有要更新的数据",
    time: "1575615020",
    data: null
    })
     */
    public function signEdit($id=null)
    {
        if(!$row = $this->sign->get($id))
        {
            $this->error('请求参数ids未获取到');
        }
        if(!$data = $this->request->request('update/a')){
            $this->error('没有要更新的数据');
        }
        $data['images'] = json_encode($data['images'],true);
        $this->sign->where('id',$id)->update($data);
        $this->success('修改成功');
    }

    /**
     * @ApiTitle    (立即签到)
     * @ApiSummary  ( 立即签到 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/signAdd)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="row[outer_id]", type="integer", required=true, description="外联任务单ID")
     * @ApiParams   (name="row[latitude]", type="string", required=true, description="纬度")
     * @ApiParams   (name="row[longitude]", type="string", required=true, description="经度")
     * @ApiParams   (name="row[images]", type="string", required=true, description="图片")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "添加成功",
    "time": "1575438362",
    "data": {
    "outer_id": "1",
    "latitude": "1",
    "longitude": "1",
    "images": "21321321,321321321,321321321",
    "userid": "yangliu",
    "createtime": 1575438364,
    "updatetime": 1575438364,
    "id": "2",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-04 13:46:04"
    }
    })
     */
    public function signAdd()
    {
        $data = $this->request->request('row/a');
        $data['userid']  = $this->auth->userid;
        $data['images'] = json_encode($data['images'],true);
        if(!$row = Sign::create($data))
        {
            $this->error('添加失败！');
        }
        $this->success('添加成功',$row);
    }

    /**
     * @ApiTitle    ( 查看签到记录)
     * @ApiSummary  ( 查看签到记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/signList/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="integer", required=true, description="任务单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     *  * @ApiReturn   ({
    "code": 1,
    "msg": "查看签到记录",
    "time": "1575701039",
    "data": {
    "sign": [
    {
    "id": 1,
    "outer_id": 1,
    "latitude": "1",
    "longitude": "2",
    "address": "",
    "images": [
    "http://oaimg.fc62.com/uploads/20191206/89d15aaf090bcdb5c6e41795a04159bc.png",
    "http://oaimg.fc62.com/uploads/20191206/6f59204606dbb57fd7c851aef338fad1.jpeg"
    ],
    "createtime": 1575488800,
    "updatetime": null,
    "userid": "yangliu",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-05 03:46:40"
    },
    {
    "id": 2,
    "outer_id": 1,
    "latitude": "1",
    "longitude": "1",
    "address": "",
    "images": [
    "http://oaimg.fc62.com/uploads/20191206/89d15aaf090bcdb5c6e41795a04159bc.png",
    "http://oaimg.fc62.com/uploads/20191206/6f59204606dbb57fd7c851aef338fad1.jpeg"
    ],
    "createtime": 1575438364,
    "updatetime": 1575438364,
    "userid": "yangliu",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-04 13:46:04"
    }
    ],
    "outer": {
    "id": 1,
    "userid": "yangliu",
    "week_id": 2,
    "school_id": 1,
    "external": "yangliu",
    "status": 1,
    "createtime": 1574908660,
    "updatetime": 1574908660,
    "filiale": 33,
    "filiale_name": "北京分公司",
    "runner": null,
    "schoolIs": null,
    "receipttime": null,
    "receiptnum": null,
    "userid_text": "杨柳",
    "week_id_text": "08.20-08.26周数据",
    "school_id_text": "北京市第四中学",
    "status_text": "新发布",
    "stateclass": "fabu",
    "external_text": "杨柳",
    "createtime_text": "2019-11-28 10:37:40"
    }
    }
    })
     */
    public function signList($outerid = null)
    {
        $list['sign'] = $this->sign->where('outer_id',$outerid)->order('id desc')->select();
        foreach ($list['sign'] as &$value)
        {
            $value['images'] = json_decode($value['images'],true);
        }
        $list['outer'] = $this->model->get($outerid);
        $this->success('查看签到记录',$list);
    }

    /**
     * @ApiTitle    ( 新增礼品明细 批量添加 批量更新)
     * @ApiSummary  ( 礼品明细 批量添加 二维数组  没有ID是新增)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/giftAdd)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="row[0][id]", type="integer", required=true, description="ID 如果是修改一定不能少ID")
     * @ApiParams   (name="row[0][sign_id]", type="integer", required=true, description="签到id")
     * @ApiParams   (name="row[0][type]", type="integer", required=true, description="礼品类别")
     * @ApiParams   (name="row[0][rule]", type="string", required=true, description="规格")
     * @ApiParams   (name="row[0][num]", type="string", required=true, description="数量")
     * @ApiParams   (name="row[1][sign_id]", type="integer", required=true, description="签到id")
     * @ApiParams   (name="row[1][type]", type="integer", required=true, description="礼品类别")
     * @ApiParams   (name="row[1][rule]", type="string", required=true, description="规格")
     * @ApiParams   (name="row[1][num]", type="string", required=true, description="数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "",
    "time": "1575537108",
    "data": {
    "id": 2,
    "userid": "yangliu",
    "week_id": 2,
    "school_id": 100,
    "external": "yangliu",
    "status": 1,
    "createtime": 1574908660,
    "updatetime": 1574908660,
    "filiale": 2,
    "filiale_name": "北京分公司2",
    "runner": null,
    "school": {
    "id": 100,
    "name": "北京一零一中学",
    "province": 1,
    "city": 2,
    "area": 8,
    "address": "颐和园路11号",
    "category": "A",
    "type": "3",
    "class": 0,
    "total_number": 0,
    "textbook_edition": null,
    "policylist": null,
    "is_schoolsdata": "1",
    "total_score": null,
    "volume": null,
    "teaching_order": null,
    "bookstore": null,
    "createtime": 1574647761,
    "updatetime": 1574650815,
    "science_num": null,
    "arts_num": null,
    "science_class": null,
    "arts_class": null,
    "up_year": 1,
    "sales_volume": null,
    "category_text": "A",
    "type_text": "高中",
    "policylist_text": "",
    "is_schoolsdata_text": "Is_schoolsdata 1",
    "volume_text": "",
    "teaching_order_text": "",
    "province_text": "北京",
    "city_text": "北京市",
    "area_text": "海淀区"
    },
    "sign": {
    "power": true
    },
    "books": [],
    "userid_text": "杨柳",
    "week_id_text": "08.20-08.26周数据",
    "school_id_text": "北京一零一中学",
    "status_text": "新发布",
    "stateclass": "fabu",
    "external_text": "杨柳",
    "createtime_text": "2019-11-28 10:37:40"
    }
    })
     */
    public function giftAdd()
    {
        $data = $this->request->request('row/a');
        if(!$row = $this->gift->saveAll($data)){
            $this->error('操作失败！');
        }
        $this->success('操作成功',$row);
    }

    /**
     * @ApiTitle    ( 删除 礼品)
     * @ApiSummary  ( 删除 礼品 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/detailDel/ids/{ids})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="ids", type="string", required=true, description="id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "删除成功",
    "time": "1575512646",
    "data": null
    })
     */
    public function giftDel($ids = null)
    {
        if(!$row = $this->gift->get($ids)){
            $this->error('请求参数ids未获取到。',$row);
        }
        $res = $this->gift->where('id',$ids)->delete();
        if($res == 0){
            $this->error('删除失败！。',$row);
        }
        $this->success('删除成功');
    }

    /**
     * @ApiTitle    (礼品明细列表)
     * @ApiSummary  ( 礼品明细列表 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/giftList/singid/{singid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="singid", type="integer", required=true, description="签到id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "礼品明细列表！",
    "time": "1575450081",
    "data": [
    {
    "id": 1,
    "sign_id": 1,
    "type": "充值卡",
    "rule": "50面值",
    "num": 100,
    "createtime": 1575449557,
    "updatetime": 1575449557
    }
    ]
    })
     */
    public function giftList($singid = null)
    {
        $list = $this->gift->where('sign_id','=',$singid)->select();
        $this->success('礼品明细列表！',$list);
    }

    /**
     * @ApiTitle    (添加 样书 赠书)
     * @ApiSummary  ( 添加 样书 赠书 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/detailAdd)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="row[sign_id]", type="integer", required=true, description="签到表ID")
     * @ApiParams   (name="row[pro_id]", type="string", required=true, description="产品表ID")
     * @ApiParams   (name="row[type]", type="string", required=true, description="类别 1=样书 2=赠书")
     * @ApiParams   (name="row[num]", type="string", required=true, description="数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "添加成功",
    "time": "1575452230",
    "data": {
    "sign_id": "1",
    "pro_id": "1",
    "type": "1",
    "num": "12",
    "createtime": 1575452231,
    "updatetime": 1575452231,
    "id": "4",
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "样书"
    }
    })
     */
    public function detailAdd()
    {
        $data = $this->request->request('row/a');
        if(!$row = Detail::create($data)){
            $this->error('添加失败！');
        }
        $this->success('添加成功',$row);
    }

    /**
     * @ApiTitle    (更新 样书 赠书)
     * @ApiSummary  ( 更新 样书 赠书)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/detailEdit)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="update[id]", type="string", required=true, description="id")
     * @ApiParams   (name="update[pro_id]", type="string", required=true, description="产品表ID")
     * @ApiParams   (name="update[num]", type="string", required=true, description="数量")
     * @ApiParams   (name="row[0][sign_id]", type="integer", required=true, description="签到表ID")
     * @ApiParams   (name="row[0][pro_id]", type="string", required=true, description="产品表ID")
     * @ApiParams   (name="row[0][type]", type="string", required=true, description="类别 1=样书 2=赠书")
     * @ApiParams   (name="row[0][num]", type="string", required=true, description="数量")
     * @ApiParams   (name="row[1][sign_id]", type="integer", required=true, description="签到表ID")
     * @ApiParams   (name="row[1][pro_id]", type="string", required=true, description="产品表ID")
     * @ApiParams   (name="row[1][type]", type="string", required=true, description="类别 1=样书 2=赠书")
     * @ApiParams   (name="row[1][num]", type="string", required=true, description="数量")
     * @ApiParams   (name="del[]", type="string", required=false, description="要删除的id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "保存成功",
    "time": "1575508627",
    "data": null
    })
     */
    public function detailEdit()
    {
        //获取要删除的数据
        $delData = $this->request->request('del/a');
        if($delData)
        {
            $this->detail->where('id','in',$delData)->delete();
        }
        //获取新增的数据
        $insterData = $this->request->request('row/a');
        if($insterData)
        {
            $this->detail->saveAll($insterData,false);
        }
        //获取更新的数据
        $updateData = $this->request->request('update/a');
        if($updateData)
        {
            $this->detail->saveAll($updateData);
        }
        $this->success('保存成功');
    }

    /**
     * @ApiTitle    ( 删除 样书 赠书)
     * @ApiSummary  ( 删除 样书 赠书 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/detailDel/ids/{ids})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="ids", type="string", required=true, description="id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "删除成功",
    "time": "1575512646",
    "data": null
    })
     */
    public function detailDel($ids = null)
    {
        if(!$row = $this->detail->get($ids)){
            $this->error('请求参数ids未获取到。',$row);
        }
        $res = $this->detail->where('id',$ids)->delete();
        if($res == 0){
            $this->error('删除失败！。',$row);
        }
        $this->success('删除成功');
    }

    /**
     * @ApiTitle    (样书 赠书 列表)
     * @ApiSummary  ( 样书 赠书 列表 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/detailtList/singid/{singid}/type/{type})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="singid", type="integer", required=true, description="签到id")
     * @ApiParams   (name="type", type="string", required=true, description="1样书2赠书 默认为1")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "样书赠书列表！",
    "time": "1575452343",
    "data": [
    {
    "id": 1,
    "sign_id": 1,
    "pro_id": 1,
    "type": 1,
    "num": 12,
    "createtime": 1575452110,
    "updatetime": 1575452110,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "样书"
    },
    {
    "id": 2,
    "sign_id": 1,
    "pro_id": 1,
    "type": 1,
    "num": 12,
    "createtime": 1575452211,
    "updatetime": 1575452211,
    "pro_name": "小学生绘本课堂  教案 一年级（六三制）J1 ",
    "pro_img": "",
    "type_text": "样书"
    }
    ]
    })
     */
    public function detailtList($singid = null,$type = 1)
    {
        $list = $this->detail->where(['sign_id'=>$singid,'type'=>$type])->select();
        $this->success('样书赠书列表！',$list);
    }

    /**
     * @ApiTitle    (添加拜访记录)
     * @ApiSummary  ( 添加拜访记录 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/seeAdd)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="row[outer_id]", type="integer", required=true, description="任务单id")
     * @ApiParams   (name="row[name]", type="string", required=true, description="姓名")
     * @ApiParams   (name="row[sex]", type="string", required=true, description="性别")
     * @ApiParams   (name="row[duty]", type="string", required=true, description="职务")
     * @ApiParams   (name="row[phone]", type="string", required=true, description="手机号码")
     * @ApiParams   (name="row[digest]", type="string", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="outer_id", type="integer", required=true, description="任务简单id")
     * @ApiReturnParams   (name="name", type="integer", required=true, description="姓名")
     * @ApiReturnParams   (name="sex", type="integer", required=true, description="性别")
     * @ApiReturnParams   (name="duty", type="integer", required=true, description="职务")
     * @ApiReturnParams   (name="phone", type="integer", required=true, description="手机号码")
     * @ApiReturnParams   (name="digest", type="integer", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="拜访记录id")
     * @ApiReturnParams   (name="userid_text", type="integer", required=true, description="添加人")
     * @ApiReturnParams   (name="createtime_text", type="integer", required=true, description="拜访时间")
     * @ApiReturn  ({
    "code": 1,
    "msg": "添加成功",
    "time": "1575699423",
    "data": {
    "outer_id": "1",
    "name": "杨柳",
    "sex": "男",
    "duty": "PHP",
    "phone": "17607118143",
    "digest": "拜访摘要",
    "userid": "yangliu",
    "createtime": 1575699424,
    "updatetime": 1575699424,
    "id": "1",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-07 14:17:04"
    }
    })
     */
    public function seeAdd()
    {
        $data = $this->request->request('row/a');
        $data['userid'] = $this->auth->userid;
        if(!$row = See::create($data)){
            $this->error('添加失败！');
        }
        $this->success('添加成功',$row);
    }

    /**
     * @ApiTitle    (拜访记录列表)
     * @ApiSummary  ( 拜访记录列表 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/seeList/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="integer", required=true, description="任务单id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="outer_id", type="integer", required=true, description="任务简单id")
     * @ApiReturnParams   (name="name", type="integer", required=true, description="姓名")
     * @ApiReturnParams   (name="sex", type="integer", required=true, description="性别")
     * @ApiReturnParams   (name="duty", type="integer", required=true, description="职务")
     * @ApiReturnParams   (name="phone", type="integer", required=true, description="手机号码")
     * @ApiReturnParams   (name="digest", type="integer", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="拜访记录id")
     * @ApiReturnParams   (name="userid_text", type="integer", required=true, description="添加人")
     * @ApiReturnParams   (name="createtime_text", type="integer", required=true, description="拜访时间")
     * @ApiReturn  ({
    "code": 1,
    "msg": "拜访记录列表！",
    "time": "1575704645",
    "data": {
    "see": [
    {
    "id": 1,
    "outer_id": 1,
    "name": "杨柳",
    "sex": "男",
    "duty": "PHP",
    "phone": "17607118143",
    "digest": "拜访摘要",
    "createtime": 1575699424,
    "updatetime": 1575699424,
    "userid": "yangliu",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-07 14:17:04"
    }
    ],
    "outer": {
    "id": 1,
    "userid": "yangliu",
    "week_id": 2,
    "school_id": 1,
    "external": "yangliu",
    "status": 1,
    "createtime": 1574908660,
    "updatetime": 1574908660,
    "filiale": 33,
    "filiale_name": "北京分公司",
    "runner": null,
    "schoolIs": null,
    "receipttime": null,
    "receiptnum": null,
    "userid_text": "杨柳",
    "week_id_text": "08.20-08.26周数据",
    "school_id_text": "北京市第四中学",
    "status_text": "新发布",
    "stateclass": "fabu",
    "external_text": "杨柳",
    "externalimg_text": "http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKC2JppppE5DugzahDO8Tlmiav2anFMR5Xmk7ruooj9vvSwFe5bHpYEGU/0",
    "createtime_text": "2019-11-28 10:37:40"
    }
    }
    })
     */
    public function seeList($outerid = null)
    {
        $list['see'] = $this->see->where(['outer_id'=>$outerid])->select();
        $list['outer'] = $this->model->get($outerid);
        $this->success('拜访记录列表！',$list);
    }

    /**
     * @ApiTitle    (拜访记录详情)
     * @ApiSummary  ( 拜访记录详情)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/see/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="integer", required=true, description="拜访记录ID")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="outer_id", type="integer", required=true, description="任务简单id")
     * @ApiReturnParams   (name="name", type="integer", required=true, description="姓名")
     * @ApiReturnParams   (name="sex", type="integer", required=true, description="性别")
     * @ApiReturnParams   (name="duty", type="integer", required=true, description="职务")
     * @ApiReturnParams   (name="phone", type="integer", required=true, description="手机号码")
     * @ApiReturnParams   (name="digest", type="integer", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="拜访记录id")
     * @ApiReturnParams   (name="userid_text", type="integer", required=true, description="添加人")
     * @ApiReturnParams   (name="createtime_text", type="integer", required=true, description="拜访时间")
     * @ApiReturn   ({
    "code": 1,
    "msg": "拜访记录查看",
    "time": "1575706000",
    "data": {
    "id": 1,
    "outer_id": 1,
    "name": "杨柳",
    "sex": "男",
    "duty": "PHP",
    "phone": "17607118143",
    "digest": "拜访摘要",
    "createtime": 1575699424,
    "updatetime": 1575699424,
    "userid": "yangliu",
    "power": false,
    "userid_text": "杨柳",
    "createtime_text": "2019-12-07 14:17:04"
    }
    })
     */
    public function see($id = null)
    {
        if(!$row = $this->see->get($id))
        {
            $this->error('请求参数ids未获取到。');
        }
        $row = $this->see->get($id);
        $row['outer'] = $this->model->get($row['outer_id']);
        $row['power'] = date('d',$row['createtime']) == date('d',time()) ? false : true;
        $this->success('拜访记录查看',$row);
    }

    /**
     * @ApiTitle    (更新拜访记录)
     * @ApiSummary  ( 更新拜访记录 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/seeEdit/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="string", required=true, description="id")
     * @ApiParams   (name="update[name]", type="string", required=true, description="姓名")
     * @ApiParams   (name="update[sex]", type="string", required=true, description="性别")
     * @ApiParams   (name="update[duty]", type="string", required=true, description="职务")
     * @ApiParams   (name="update[phone]", type="string", required=true, description="手机号码")
     * @ApiParams   (name="update[digest]", type="string", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="outer_id", type="integer", required=true, description="任务简单id")
     * @ApiReturnParams   (name="name", type="integer", required=true, description="姓名")
     * @ApiReturnParams   (name="sex", type="integer", required=true, description="性别")
     * @ApiReturnParams   (name="duty", type="integer", required=true, description="职务")
     * @ApiReturnParams   (name="phone", type="integer", required=true, description="手机号码")
     * @ApiReturnParams   (name="digest", type="integer", required=true, description="拜访摘要")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="拜访记录id")
     * @ApiReturnParams   (name="userid_text", type="integer", required=true, description="添加人")
     * @ApiReturnParams   (name="createtime_text", type="integer", required=true, description="拜访时间")
     * @ApiReturn  ({
    "code": 1,
    "msg": "修改成功",
    "time": "1575706024",
    "data": {
    "id": 1,
    "outer_id": 1,
    "name": "21212",
    "sex": "",
    "duty": "",
    "phone": "",
    "digest": "",
    "createtime": 1575699424,
    "updatetime": 1575699424,
    "userid": "yangliu",
    "userid_text": "杨柳",
    "createtime_text": "2019-12-07 14:17:04"
    }
    })
     */
    public function seeEdit($id = null)
    {
        if(!$row = $this->see->get($id))
        {
            $this->error('请求参数ids未获取到。',$row);
        }
        if(!$data = $this->request->request('update/a')){
            $this->error('没有要更新的数据。',$row);
        }
        $this->see->where('id',$id)->update($data);
        $row = $this->see->get($id);
        $this->success('修改成功',$row);
    }

    /**
     * @ApiTitle    ( 提交审核 )
     * @ApiSummary  ( 提交审核 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/outerFlow/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="string", required=true, description="outerid")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ()
     */
    public function outerFlow($outerid = null)
    {
        /**
         * 查询条件 （表名 + 部门id + status = 0） 获取流程id
         * 新建流程id  -> 提醒审核人 （提醒抄送人）
         */
        //查询任务单中的部门id
        $outerRow = $this->model->get($outerid);
        //查询流程获取到流程id
        $flowRow = $this->flow->where(['dep_id'=>$outerRow['filiale'],'type'=>$this->tableName,'status'=>0])->find();
        if(!$flowRow)
        {
            $this->error('还没有流程或流程已禁用');
        }
        //wf_id  流程ID 表flow 2   wf_fid  当前任务单操作表id
        $data = ['wf_id'=>$flowRow->id,'wf_fid'=>$outerid,'wf_type'=>$this->tableName,'new_type'=>0,'check_con'=>'外联任务单生成'];
        $newFlow = new workflow();
        $res = $newFlow->startworkflow($data,$this->auth->userid,2);
        //工作流生成成功
        if($res['code'] != 1)
        {
            $this->error('失败！');
        }
        $flowInfo = $newFlow->workflowInfo($outerid,$this->tableName);

        //发送消息 提醒审核人员  $flowInfo['process']; 第一步的数据
        // 1.发送消息的人 2.消息的详细地址  3.要发送的内容
        $url = 'http://oa.fc62.com/outer/#/Examine?outerid='.$outerid;
        $title = '有新的任务单待审核';
        $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div><div class=\"normal\">".$this->auth->username."任务单已完成，等待审核。</div><div class=\"highlight\">请在当天内完成审核</div>";
        $this->ExternalMsg($flowInfo['process']['auto_sponsor_ids'],$url,$title,$text);
        //给抄送给合跑外联发信息
        if($outerRow->external)
        {
            $user = str_replace(',','|',$outerRow->external);
            $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div><div class=\"normal\">".$this->auth->username."合跑任务单已完成，等待审核。</div><div class=\"highlight\">".$this->auth->username."抄送外联任务单详情</div>";
            $this->ExternalMsg($user,$url,$title,$text);
        }
        $outerRow->status = 1;
        $outerRow->save();
        //返回成功数据
        $this->success('提交审核！');
    }

    /**
     * @ApiTitle    ( 审核详情 )
     * @ApiSummary  ( 审核详情 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/outer/outerFlowInfo/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="string", required=true, description="outerid")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ()
     */
    public function outerFlowInfo($outerid = null)
    {
        $newFlow = new workflow();
        $flowInfo = $newFlow->workflowInfo($outerid,$this->tableName);
        $outerRow = $this->model->get($outerid);
        if(isset($flowInfo['bill_check']))
        {
            $logList = $newFlow->FlowLog('logs',$outerid,$this->tableName);
            $this->error('审核已经结束。',['log'=>$logList]);
        }
        unset($flowInfo['singuser']);
        $arr = [];
        foreach ($flowInfo['preprocess'] as $key=>$preprocess) {
            $arr[] = [
                'id'=>$key,
                'value'=>$preprocess
            ];
        }
        $flowInfo['week'] = [];
        $flowInfo['userlist'] = [];
        $flowInfo['preprocess'] = $arr;
        $flowInfo['market'] = [];//销售
        $flowInfo['school'] = [];
        if($flowInfo['status']['wf_action'] == 'finance')
        {
            $flowInfo['week'] = Season::where(['extract_week'=>$outerRow['week_id']])->select();
            $userList = explode(',',$outerRow['external'].','.$outerRow['runner']);
            $userList = array_filter($userList);
            if(!$school = \app\admin\model\finance\extract\School::get(['outer_id'=>$outerid])){
                foreach ($userList as $key=>$value)
                {
                    $flowInfo['userlist'][$key] = [
                        'userid'=>$value,
                        'name'=>Admin::userName($value),
                        'img'=>Admin::where('userid',$value)->value('avatar'),
                        'num'=>count($userList) == 1 ?'100':'',
                        'type'=>1
                    ];
                }
            }else{
                $flowInfo['school'] = $school;
                //查询type = 1
                $schoolData = \app\admin\model\finance\extract\school\Data::where(['extract_school'=>$school['id']])->select();
                //查询外联人员比例
                foreach ($schoolData as $key=>$value)
                {
                    if($value['type'] == 2){
                        $flowInfo['market'][] = [
                            'price'=>$value['price'],
                            'num'=>$value['num'],
                            'type'=>$value['type']
                        ];
                    }
                    if($value['type'] == 1)
                    {
                        $flowInfo['userlist'][] = [
                            'userid'=>$value['userid'],
                            'name'=>Admin::userName($value['userid']),
                            'img'=>Admin::where('userid',$value['userid'])->value('avatar'),
                            'num'=>$value['proportion'],
                            'type'=>$value['type']
                        ];
                    }
                }
            }

        }

        $this->success('审核详情',$flowInfo);
    }

    /**
     * @ApiTitle    (确认审核)
     * @ApiSummary  ( 驳回 row[wf_backflow] 必须传  审核通过 row[check_con]  row[submit_to_save]  财务审核 除了row[wf_backflow] 其他都得传 )
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/outer/doCheck/outerid/{outerid})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="outerid", type="string", required=true, description="outerid")
     * @ApiParams   (name="row[check_con]", type="string", required=true, description="审核内容")
     * @ApiParams   (name="row[wf_backflow]", type="string", required=false, description="回退步骤")
     * @ApiParams   (name="row[submit_to_save]", type="string", required=true, description="ok=审核成功 back=审核拒绝")
     * @ApiParams   (name="school[book_num]", type="string", required=false, description="手边题本数量")
     * @ApiParams   (name="school[book_price]", type="string", required=false, description="手边题本单科成本")
     * @ApiParams   (name="school[people_num]", type="integer", required=false, description="来人数")
     * @ApiParams   (name="school[season_id]", type="integer", required=false, description="场次id")
     * @ApiParams   (name="school[gift_books]", type="string", required=false, description="赠书")
     * @ApiParams   (name="external[0][type]", type="integer", required=false, description="1")
     * @ApiParams   (name="external[0][userid]", type="string", required=false, description="userid")
     * @ApiParams   (name="external[0][proportion]", type="integer", required=false, description="百分比 默认0 外联信息")
     * @ApiParams   (name="market[0][type]", type="string", required=false, description="2")
     * @ApiParams   (name="market[0][price]", type="string", required=false, description="销售价钱信息")
     * @ApiParams   (name="market[0][num]", type="integer", required=false, description="数量")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ()
     */
    public function doCheck($outerid = null)
    {
        $newFlow = new workflow();
        $flowInfo = $newFlow->workflowInfo($outerid,$this->tableName);
        if(isset($flowinfo['bill_check']))
        {
            $this->success('没有此审核流程。');
        }
//        echo "<pre>";
//        print_r($flowInfo);exit;
        $url = 'http://oa.fc62.com/outer/#/Examine?outerid='.$outerid;
        $data = $this->request->request('row/a');
        $data['wf_title'] = $flowInfo['flow_name'];
        $data['wf_fid'] = $outerid;
        $data['wf_type'] = $this->tableName;
        $data['flow_id'] = $flowInfo['flow_id'];
        $data['flow_process'] = $flowInfo['flow_process'];
        $data['run_id'] = $flowInfo['run_id'];
        $data['run_process'] = $flowInfo['run_process'];
        $data['npid'] = $flowInfo['nexprocess']['id'];
        $data['wf_mode'] = $flowInfo['wf_mode'];
        $data['sup'] = '';
        //$data['wf_backflow'] = '';//请选择回退步骤
        //$data['btodo'] = '';//选择退了到哪一步
        //$data['check_con'] = '审核内容';
        //$data['submit_to_save'] = 'ok';
        $data['sing_st'] = '';//会签
        $data['art'] = '';//附件
        $row = $this->model->get($outerid);
        //判断是否审核通过
        if($data['submit_to_save'] == 'ok')
        {
            //操作审核通过Array ( [run_id] => 3 [run_flow_process] => 8 )
            Db::startTrans();
            $res = $newFlow->workdoaction($data,$this->auth->userid);
            if($flowInfo['status']['wf_action'] == 'finance')
            {
                $array['external'] = $this->request->request('external/a');
                $array['school'] = $this->request->request('school/a');
                $array['market'] = $this->request->request('market/a');
                $array['outerid'] = $outerid;
                if(!$this->retailScanningData($array))
                {
                    Db::rollback();
                    $this->error('审核失败！');
                }
            }
            Db::commit();
            //流程审核结束 最后一次审核
            if(!$res['run_flow_process'])
            {
                //通知给外联已经结束
                $title = '审核完成';
                $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div>
                      <div class=\"normal\">".$this->auth->username."任务单审核已完成。</div>
                      <div class=\"highlight\">".$data['check_con']."</div>";
                $this->ExternalMsg($row['external'],$url,$title,$text);
                $this->success('审核完成！');
            }else{
                //审核通过 通知下一位审核人
                $title = '审核通过';
                $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div><div class=\"normal\">".$this->auth->username."任务单已完成，等待审核。</div><div class=\"normal\">".$data['check_con']."</div><div class=\"highlight\">请在当天内完成操作</div>";
                $this->ExternalMsg($flowInfo['nexprocess']['auto_sponsor_ids'],$url,$title,$text);
                $this->success('审核通过！');
            }
        }
        if($data['submit_to_save'] == 'back')
        {
            //操作审核拒绝 Array ( [run_id] => 3 [run_flow_process] => 8 )
            if($data['wf_backflow'] == '' && $data['wf_backflow'] != 0)
            {
                $this->error('请选择回退步骤');
            }
            $res = $newFlow->workdoaction($data,$this->auth->userid);
            $user = $row['external'];//外联
            if($data['wf_backflow'] != 0)
            {
                //驳回
                $pre_n = Db::name('run_process')->where('id','eq',$data['wf_backflow'])->find();
                $user = $pre_n['uid'];
            }else{
                $row->status = -1;
                $row->save();
            }
        }
        $title = '审核拒绝';
        $text  = "<div class=\"gray\">".date('Y年m月d日',time())."</div><div class=\"normal\">".$this->auth->username."拒绝此任务单。</div><div class=\"normal\">".$data['check_con']."</div><div class=\"highlight\">请在当天内完成操作</div>";
        $this->ExternalMsg($user,$url,$title,$text);
        $this->success('审核拒绝！');
    }

    /**
     * 外联发布新任务
     * @param $external 外联
     * @param $runner 合跑外联
     * @return mixed
     */
    protected function ExternalMsg($external,$url,$title,$text)
    {
        $msgUser = str_replace(',','|',$external);
        $array = [
            'touser'=>$msgUser,//成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）
            'msgtype'=>'textcard',
            'agentid'=>Env::get('outer.agent_id'),
            'textcard'=>[
                'title'=>$title,
                'description'=>$text,
                'url'=>$url,
                'btntxt'=>'点击查看'
            ],
            'safe'=>1,//是否加密
        ];
        $token = $this->token['access_token'];
        $response = \fast\Http::post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$token,json_encode($array,true));
        return json_decode($response,true);
    }

    protected function retailScanningData(array $array)
    {
        $outerRow = $this->model->get($array['outerid']);
        $SchoolNew = new \app\admin\model\finance\extract\school\Data();
        //有就修改
        if(!$school = \app\admin\model\finance\extract\School::get(['outer_id'=>$array['outerid']]))
        {
            $schoolRow = $this->school->get($outerRow['school_id']);
            //创建
            $data = [
                'extract_week'=>$outerRow['week_id'],
                'school_id'=>$outerRow['school_id'],//学校id
                'publish'=>$this->auth->userid,//添加人
                'z_publish'=>$this->auth->userid,//最后添加人
                'coming_num'=>$schoolRow['total_number'],//学校总人数
                'book_num'=>$array['school']['book_num'],//手边题本数量
                'book_price'=>$array['school']['book_price'],//手边题本单科成本
                'people_num'=>$array['school']['people_num'],//学校来人数
                'season_id'=>$array['school']['season_id'],//场次id
                'gift_books'=>$array['school']['gift_books'],//赠书数量
                'outer_id'=>$array['outerid'],//任务单id
            ];
            if (!$res = \app\admin\model\finance\extract\School::create($data))
            {
                return false;
            }
            $id = $res->id;

        }else{
            $id = $school->id;
            //创建
            $data = [
                'z_publish'=>$this->auth->userid,//最后添加人
                'book_num'=>$array['school']['book_num'],//手边题本数量
                'book_price'=>$array['school']['book_price'],//手边题本单科成本
                'people_num'=>$array['school']['people_num'],//学校来人数
                'season_id'=>$array['school']['season_id'],//场次id
                'gift_books'=>$array['school']['gift_books'],//赠书数量
            ];
            $school->save($data);
            //删除数据
            $SchoolNew->where('extract_school',$id)->delete();
        }

        //添加新的数据
        foreach ($array['external'] as &$value)
        {
            $value['extract_school'] = $id;
        }

        if(!$SchoolNew->saveAll($array['external']))
        {
            return false;
        }
        //添加新的数据
        foreach ($array['market'] as &$value)
        {
            $value['extract_school'] = $id;
        }
        if(!$SchoolNew->saveAll($array['market'])){
            return false;
        }
        return true;
    }

}
